package server;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * Minicat的主类
 */
public class Bootstrap {

    /**定义socket监听的端口号, 默认为8080*/
    private int port = 8080;

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }


    /**
     * Minicat启动需要初始化展开的一些操作
     */
    public void start() throws Exception {
        // 解析server.xml，
        loadServerConfig();

        // 定义一个线程池
        int corePoolSize = 10; // 核心线程数
        int maximumPoolSize =50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();


        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );


        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("=====>>>Minicat start on port：" + port);

        System.out.println("=========>>>>>>使用线程池进行多线程改造");
        /*
            多线程改造（使用线程池）
         */
        while(true) {
            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket, mapper);
            threadPoolExecutor.execute(requestProcessor);
        }
    }

    private Mapper mapper = new Mapper();

    /**
     * 加载解析web.xml
     */
    private void loadServerConfig() {
        try {
            InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("server.xml");
            SAXReader saxReader = new SAXReader();
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();
            // 参考tomcat，一个Engine可以有多个Host标签
            List<Element> hostElements = rootElement.selectNodes("//Host");
            for (Element hostElement : hostElements) {
                //初始化一个Host对象
                Host host = new Host();
                //解析name以及appBase内容
                String hostName = hostElement.attributeValue("name");
                String appBase = hostElement.attributeValue("appBase");

                // 解析context标签
                List<Element> contextElements = hostElement.selectNodes("//Context");
                for (Element contextElement : contextElements) {
                    // 目前server.xml中我们定义的docBase用的就是绝对路径，这里也按相对路径来处理
                    String docBase = contextElement.attributeValue("docBase");
                    // context标签中定义的path，相当于应用名称，紧跟在url端口后面，如localhost:8080/demo1/lagou中的/demo1
                    String path = contextElement.attributeValue("path");

                    File file = new File(docBase);
                    if (file.isDirectory() && file.exists()) {
                        Context context = new Context();
                        // /demo1
                        context.setPath(path);
                        // 解析每一个应用的web.xml文件，封装servlet对象
                        File webXml = new File(docBase, "web.xml");
                        loadServlet(webXml, context);
                        host.getContextMapping().put(path, context);
                    }

                }
                host.setName(hostName);
                mapper.getHostMapping().put(hostName, host);
            }

        } catch (DocumentException e) {
            e.printStackTrace();
        }

    }

    /**
     * 加载解析web.xml，初始化Servlet
     */
    private void loadServlet(File webXmlFile, Context context) {
        SAXReader saxReader = new SAXReader();

        try {
            Document document = saxReader.read(webXmlFile);
            Element rootElement = document.getRootElement();
            MyClassLoader myClassLoader = new MyClassLoader();
            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            for (int i = 0; i < selectNodes.size(); i++) {
                Element element =  selectNodes.get(i);
                // <servlet-name>lagou</servlet-name>
                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();
                // <servlet-class>server.LagouServlet</servlet-class>
                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletclassElement.getStringValue();


                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                // /lagou
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
                Class<?> aClass = myClassLoader.findClass(webXmlFile.getParent() + "/", servletClass);
                context.getServletMapping().put(urlPattern, (HttpServlet) aClass.newInstance());
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }

    }


    /**
     * Minicat 的程序启动入口
     * @param args
     */
    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();
        try {
            // 启动Minicat
            bootstrap.start();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
